package com.icesoft.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.icesoft.framework.core.service.impl.BaseServiceImpl;
import com.icesoft.framework.core.vo.JsonResult;
import com.icesoft.system.dto.RoleDTO;
import com.icesoft.system.entity.*;
import com.icesoft.system.mapper.RoleMapper;
import com.icesoft.system.permission.entity.ApiPermission;
import com.icesoft.system.service.RoleService;
import com.icesoft.system.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * appuserService业务层处理
 *
 * @author madiao
 * @date 230212
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, Role> implements RoleService {

	private final RoleMenuServiceImpl roleMenuService;

	private final RoleOrgServiceImpl roleOrgService;

	private final PermissionServiceImpl permissionService;

	@Transactional
	public JsonResult<?> updateMenu(Long id, RoleDTO dto) {
		LambdaQueryWrapper<RoleMenu> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(RoleMenu::getRoleId, id);
		roleMenuService.remove(queryWrapper);
		for (Long menuId : dto.getMenuIdList()) {
			roleMenuService.createEntity(new RoleMenu(dto.getId(), menuId));
		}
		return JsonResult.OK();
	}

	@Transactional
	public JsonResult<?> updateOrg(Long id, RoleDTO dto) {
		Role entity = this.getEntity(id);
		LambdaQueryWrapper<RoleOrg> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(RoleOrg::getRoleId, id);
		roleOrgService.remove(queryWrapper);
		if (dto.getOrgIdList() == null) {
			entity.setRoleType(dto.getRoleType());
		} else {
			for (Long orgId : dto.getOrgIdList()) {
				roleOrgService.createEntity(new RoleOrg(id, orgId));
			}
		}
		return JsonResult.OK();
	}

	@Transactional
	public JsonResult<?> updatePermission(Long id, RoleDTO dto) {
		LambdaQueryWrapper<Permission> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(Permission::getRoleId, id);
		permissionService.remove(queryWrapper);
		for (ApiPermission permission : dto.getPermissionList()) {
			permissionService.createEntity(new Permission(id, permission.getUri()));
		}
		return JsonResult.OK();
	}

	public boolean isExistByName(String name) {
		User user = SecurityUtils.getCurrentUser();
		return lambdaQuery().eq(Role::getName, name).eq(Role::getCompanyId, user.getCompanyId()).exists();
	}
}
